package com.unhz.taigu.controller.system;

import com.unhz.generator.pojo.SysRole;
import com.unhz.generator.pojo.SysUser;
import com.unhz.generator.utils.*;
import com.unhz.generator.utils.service.FileUtilService;
import com.unhz.taigu.service.SysRoleService;
import com.unhz.taigu.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author: 曹显贵
 * @Description: 管理员
 * @Date: Created in 14:48 2018/1/24 0024
 * @Modified By:
 */
@Controller
@RequestMapping("/sysUserController")
public class SysUserController {

    private Logger logger = LoggerFactory.getLogger(SysUserController.class);

    /**
     * 用户业务层
     **/
    @Autowired
    private SysUserService sysUserService;
    /**
     * 角色业务层
     **/
    @Autowired
    private SysRoleService sysRoleService;
    /**
     * 文件上传工具业务层
     **/
    @Autowired
    private FileUtilService fileUtilService;

    /**
     * 进入增加页面
     * @param model
     * @return
     */
    @RequestMapping("/toAdd")
    @RequiresPermissions("sysuser:add")
    public String toAdd(Model model) {
        List<SysRole> sysRoles = sysRoleService.findAllRole();
        model.addAttribute("sysRoles", sysRoles);
        return "system/sysuser/user-add.jsp";
    }

    /**
     * 增加管理员
     * @param sysUser
     * @param model
     * @return
     */
    @RequestMapping("/insert")
    @RequiresPermissions("sysuser:add")
    public String insert(SysUser sysUser, Model model) {
        sysUser.setUserPassword(MD5.MD5Encode(sysUser.getUserPassword()));
        String index = sysUserService.insertUser(sysUser);
        return "redirect:findPageAllSysUser";
    }

    /**
     * 进入修改页面
     * @param model
     * @param sysUserId
     * @return
     */
    @RequestMapping("/toUpdate")
    @RequiresPermissions("sysuser:update")
    public String toUpdate(Model model,
                           @RequestParam("sysUserId")Integer sysUserId) {
        SysUser sysUser = sysUserService.selectByUserId(sysUserId);
        List<SysRole> sysRoles = sysRoleService.findAllRole();
        model.addAttribute("sysRoles", sysRoles);
        model.addAttribute("sysUser",sysUser);
        return "system/sysuser/user-update.jsp";
    }

    //执行修改
    @RequestMapping("/Update")
    @RequiresPermissions("sysuser:update")
    public String Update(SysUser sysUser) {
        int count = sysUserService.updateUserById(sysUser);
        return "redirect:findPageAllSysUser";
    }

    //查询所有用户
    @RequiresPermissions("sysuser:findAll")
    @RequestMapping("/findPageAllSysUser")
    public String findPageAllSysUser(Model model,
                                     @RequestParam(value = "pageNo",defaultValue = "1",required = false)String pageNo,
                                     @RequestParam(value = "keywords",defaultValue = "",required = false)String keywords,
                                     HttpServletRequest request) throws UnsupportedEncodingException {
        if("GET".equals(request.getMethod())){
            keywords = new String(keywords.getBytes("iso-8859-1"),"utf-8");
        }
        Page<SysUser> page = sysUserService.findPageAllSysUser(pageNo, PageSize.pageSize,keywords);
        //查询所有角色
        List<SysRole> sysRoles = sysRoleService.findAllRole();
        model.addAttribute("page",page);
        model.addAttribute("sysRoles",sysRoles);
        model.addAttribute("keywords",keywords);
        return "system/sysuser/user-list.jsp";
    }


    //启用禁用管理员
    @RequestMapping("/updateStatus")
    @RequiresPermissions("sysuser:isenable")
    @ResponseBody
    public JsonResult updateStatus(@RequestParam("sysUserId")Integer sysUserId){

        SysUser sysUser = sysUserService.selectByUserId(sysUserId);
        String result = sysUserService.updateUserStatus(sysUser);
        if("success".equals(result)){
            return JsonResult.success("修改状态成功");
        }else{
            return JsonResult.failure("修改状态失败!");
        }
    }
    //删除管理员
    @RequestMapping("/delete")
    @RequiresPermissions("sysuser:delete")
    @ResponseBody
    public JsonResult delete(@RequestParam("sysUserId")Integer sysUserId){
        String result = sysUserService.deleteUserById(sysUserId);
        if("success".equals(result)){
            return JsonResult.success("删除成功");
        }
        return JsonResult.failure("删除失败");
    }


    @RequestMapping("/uplodaImage")
    public void uploadUserHeadImg(@RequestParam("filename") MultipartFile file,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetname = fileUtilService.upload(file, path);
        String fileNames = file.getOriginalFilename();
        String fileName = fileNames.substring(0, fileNames.lastIndexOf("."));
        String fileFormat = fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
        response.getWriter().print(CommonFileAddress.FilePath + "/" + targetname + '|' + fileName + '|' + fileFormat);
    }
    //修改密码
    @RequestMapping("/updateKeywords")
    public String updateKeywords(@RequestParam("sysUserId")Integer sysUserId, Model model){
        SysUser sysUser = sysUserService.selectByUserId(sysUserId);
        model.addAttribute("sysUser",sysUser);
        return "system/sysuser/user-keywords.jsp";
    }
    //检测旧密码是否正确
    @RequestMapping("/oldPassword")
    @ResponseBody
    public JsonResult oldPassword(@RequestParam("oldPassword")String oldPassword,HttpServletRequest request){
        SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUserManage");
        oldPassword = MD5.MD5Encode(oldPassword);
        sysUser = sysUserService.selectByUserId(sysUser.getId());
        if(oldPassword.equals(sysUser.getUserPassword())){
            return JsonResult.success("密码正确");
        }
        return JsonResult.failure("密码错误");
    }
    //执行修改
    @RequestMapping("/updatePasswords")
    @ResponseBody
    public JsonResult updateKeywords(SysUser sysUser){
        logger.info(sysUser.getUserPassword());
        sysUser.setUserPassword(MD5.MD5Encode(sysUser.getUserPassword()));
        String index = sysUserService.updateUserPassword(sysUser);
        if("success".equals(index)){
            return JsonResult.success("修改密码成功");
        }
        return JsonResult.failure("修改密码失败");
    }

    //根据名称查询用户
    @RequestMapping("/findSysUserByUserName")
    @ResponseBody
    public JsonResult findSysUserByUserName(@RequestParam(value = "userName",defaultValue = "",required = true)String userName) {
        SysUser sysUser = sysUserService.selectByUserName(userName);
        if(sysUser!=null){
            return JsonResult.success("名称已存在");
        }
        return JsonResult.failure("名称可用");
    }
}

